﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using System.Xml;
using nkstdgia.common.DuongKhaoSat;
using nkstdgia.common.ThamDinhGia.BusinessLogic;
using nkstdgia.common.ThamDinhGia.BusinessObjects;
using wsRK.Web;
using wsRK.wsControls;

namespace nkstdgia.main
{
    public partial class ctGiaDoanDuong : WebPage
    {
        #region Variable
        #endregion

        #region Construction
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this._bindDoanDuongData(null);
                this._bindHistoryData("");
                this._getDataQuan();
                this.ddlQuan.SelectedIndex = 0;
                this.ddlDuong.SelectedIndex = 0;
                if (Request.QueryString["isAdd"] != null)
                    base.showMessage(true, "OK", "Dữ liệu đã được cập nhật");
            }
        }
        #endregion

        #region Get Data
        private void _getDataQuan()
        {
            List<THAM_SO> lsThamSo = ThamDinhGiaFacade.GetTHAM_SOBL().GetList();
            lsThamSo = (from t in lsThamSo
                        where t.LOAI_THAM_SO == "LOAI_QUAN"
                        orderby t.SEQUENCE ascending
                        select t).ToList();
            this.ddlQuan.DataSource = lsThamSo;
            this.ddlQuan.DataBind();
            this._getDataDuong();
        }

        private void _getDataDuong()
        {
            int intMaThamSoQuan = int.Parse(this.ddlQuan.SelectedValue);
            this._getDataDuong(intMaThamSoQuan);
        }

        private void _getDataDuong(int intMaQuan)
        {
            DuongKhaoSatDataService dksDS = new DuongKhaoSatDataService();
            List<DuongKhaoSatInfo> listDKS = dksDS.searchDuong4GiaDat(intMaQuan);
            List<DuongKhaoSatInfo> listDKSShowed = new List<DuongKhaoSatInfo>();
            for (int i = 0; i < listDKS.Count; i++)
            {
                DuongKhaoSatInfo dks = listDKS[i];
                //if (dks.QUAN == intMaQuan && dks.PHUONG == MaPhuong)
                {
                    //dks.DUONG = dks.DUONG+ " _ " + dks.DOAN_DUONG;
                    listDKSShowed.Add(dks);
                }

            }
            if (listDKSShowed.Count > 0)
            {
                this.ddlDuong.DataSource = listDKSShowed;
                this.ddlDuong.DataBind();
                this.ddlDuong.Enabled = true;
                this.btnAdd.Visible = true;
                this._getListGiaDoanDuong();
            }
            else
            {
                this.ddlDuong.Items.Clear();
                this.ddlDuong.Enabled = false;
                this.btnAdd.Visible = false;
            }
        }

        #endregion

        #region Event

        protected void btnTenDoanDuongPopup_Click(object sender, EventArgs e)
        {
            try
            {
                string strDuong = this.ddlDuong.SelectedItem.Text;
                double giaDat = 0.0;
                if (!String.Empty.Equals(this.txtGiaDatPopup.Text))
                {
                    giaDat = this.txtGiaDatPopup.Value;
                    if (!giaDat.Equals(0.0))
                    {
                        GiaDoanDuongInfo gdd = new GiaDoanDuongInfo();
                        gdd.DUONG = strDuong.Trim();
                        gdd.DOAN_DUONG = this.txtTenDoanDuongPopup.Text.Trim();
                        gdd.GIA_DAT = giaDat;
                        System.Web.Security.MembershipUser userLogin = wsRK.AppUser.MembershipDataservice.getUser(User.Identity.Name);
                        Guid userID = (Guid)userLogin.ProviderUserKey;
                        gdd.QUAN = ddlQuan.SelectedValue;
                        gdd.NGUOI_KHOI_TAO = userID;
                        gdd.NGAY_KHOI_TAO = DateTime.Now;
                        gdd.NGAY_CAP_NHAT = DateTime.Now;
                        gdd.ACTIVE_FLAG = "Y";

                        GiaDoanDuongDataService gddDS = new GiaDoanDuongDataService();
                        gddDS.addDoanDuong(gdd);
                        this._getListGiaDoanDuong();

                        //ThamDinhGiaFacade.GetGIA_DOAN_DUONGL().Add(gdd);
                        base.showMessage(true, "OK", "Thông tin đã lưu.");
                        //this._getGiaDoanDuongByMaDKS(intMaDKS);
                    }
                    else
                    {
                        base.showMessage(true, "OK", "Bạn chưa nhập giá đất.");
                    }
                }
                else
                {
                    base.showMessage(true, "OK", "Bạn chưa nhập giá đất.");
                }

            }
            catch (Exception ex)
            {
                base.showMessage(true, "OK", "Có lỗi trong khi gửi dữ liệu!!!");
            }
            finally
            {
                base.hideLoader();
            }
        }

        protected void ddlQuan_SelectedIndexChanged(object sender, EventArgs e)
        {
            this._bindDoanDuongData(null);
            this._bindHistoryData("");
            this._getDataDuong();
        }

        protected void ddlPhuong_SelectedIndexChanged(object sender, EventArgs e)
        {
            this._bindDoanDuongData(null);
            this._getDataDuong();
        }

        protected void ddlDuong_SelectedIndexChanged(object sender, EventArgs e)
        {
            //this._bindHistoryData("");
            this._getListGiaDoanDuong();
        }

        protected void _btnEdit_Click(object sender, EventArgs e)
        {
        }

        protected void _btnHistory_Click(object sender, EventArgs e)
        {
            ImageButton btnIMG = (sender as ImageButton);

            HiddenField hdDOAN_DUONG = btnIMG.Parent.FindControl("hdDOAN_DUONG") as HiddenField;

            if (hdDOAN_DUONG.Value != "")
            {
                this.lblHistory.Text = "Lịch sử của đoạn đường: " + hdDOAN_DUONG.Value;
            }
            else
            {
                this.lblHistory.Text = "Lịch sử";
            }
            this._bindHistoryData(btnIMG.CommandArgument.ToString());
        }

        protected void _btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                 GiaDoanDuongDataService gddDS = new GiaDoanDuongDataService();
                 ImageButton btnIMG = (sender as ImageButton);
                 gddDS.deleteGiaDoanDuong(btnIMG.CommandArgument.ToString());

                 this._getListGiaDoanDuong();
                 this._bindHistoryData("");
            }
            catch (Exception)
            {
                 base.showMessage(true, "OK", "Có lỗi trong khi gửi dữ liệu!!!");
            }
        }

        protected void lstGiaDat_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            this.lstGiaDat.EditIndex = e.NewEditIndex;
            this._getListGiaDoanDuong();
        }

        protected void lstGiaDat_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {

            this.lstGiaDat.EditIndex = -1;
            this._getListGiaDoanDuong();
        }

        protected void lstGiaDat_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            try
            {
                string strDuong = this.ddlDuong.SelectedItem.Text;
                double giaDat = 0.0;
                wsTxtDouble txtGiaDatEdit = this.lstGiaDat.EditItem.FindControl("txtGiaDat") as wsTxtDouble;
                if (!String.Empty.Equals(txtGiaDatEdit.Text))
                {
                    giaDat = txtGiaDatEdit.Value;
                    if (!giaDat.Equals(0.0))
                    {
                        GiaDoanDuongInfo gdd = new GiaDoanDuongInfo();
                        gdd.DUONG = strDuong.Trim();
                        TextBox txtDOAN_DUONG = this.lstGiaDat.EditItem.FindControl("txtDOAN_DUONG") as TextBox;
                        gdd.DOAN_DUONG = txtDOAN_DUONG.Text.Trim();
                        gdd.GIA_DAT = giaDat;
                        System.Web.Security.MembershipUser userLogin = wsRK.AppUser.MembershipDataservice.getUser(User.Identity.Name);
                        Guid userID = (Guid)userLogin.ProviderUserKey;
                        gdd.QUAN = ddlQuan.SelectedValue;
                        gdd.NGUOI_KHOI_TAO = userID;
                        gdd.NGAY_KHOI_TAO = DateTime.Now;
                        gdd.NGAY_CAP_NHAT = DateTime.Now;
                        gdd.ACTIVE_FLAG = "Y";

                        GiaDoanDuongDataService gddDS = new GiaDoanDuongDataService();
                        gddDS.addDoanDuong(gdd);

                        this.lstGiaDat.EditIndex = -1;
                        this._getListGiaDoanDuong();

                        //ThamDinhGiaFacade.GetGIA_DOAN_DUONGL().Add(gdd);
                        base.showMessage(true, "OK", "Thông tin đã lưu.");
                        //this._getGiaDoanDuongByMaDKS(intMaDKS);
                    }
                    else
                    {
                        base.showMessage(true, "OK", "Bạn chưa nhập giá đất.");
                    }
                }
                else
                {
                    base.showMessage(true, "OK", "Bạn chưa nhập giá đất.");
                }

            }
            catch (Exception ex)
            {
                base.showMessage(true, "OK", "Có lỗi trong khi gửi dữ liệu!!!");
            }
            finally
            {
                base.hideLoader();
            }
        }

        #endregion

        #region Other
        private void _getListGiaDoanDuong()
        {
            GiaDoanDuongDataService GDDds = new GiaDoanDuongDataService();
            DataSet ds = GDDds.getListGiaDoanDuong(ddlQuan.SelectedValue, this.ddlDuong.SelectedItem.Text);
            if (ds.Tables.Count > 0)
            {
                this._bindDoanDuongData(ds.Tables[0]);
            }
            else
            {
                this._bindDoanDuongData(null);
            }

            //if (objGDD != null)
            //{
            //    this.txtGiaDat.Text = string.Format("{0:###,###,##0.000}", objGDD.GIA_DAT);
            //    this._bindHistoryData(objGDD.HISTORY);
            //}
            //else
            //{
            //    this.txtGiaDat.Text = "";
            //}
        }

        private void _bindDoanDuongData(DataTable dt)
        {
            this.lstGiaDat.DataSource = dt;
            this.lstGiaDat.DataBind();
        }

        private void _bindHistoryData(string history)
        {
            if (history == "")
            {
                this.lblHistory.Text = "Lịch sử";
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("RowNumber");
            dt.Columns.Add("Date");
            dt.Columns.Add("Value");
            if (history != null)
            {
                if (history != "")
                {
                    XmlDocument xdoc = new XmlDocument();
                    xdoc.LoadXml(history);
                    XmlNodeList xnodelist = xdoc.SelectNodes("//root/item");
                    int i = 1;
                    foreach (XmlNode item in xnodelist)
                    {
                        string strDate = item.Attributes["date"].Value;
                        // YYYYmmDD
                        strDate = strDate.Substring(6, 2) + "/" + strDate.Substring(4, 2) + "/" + strDate.Substring(0, 4);
                        dt.Rows.Add(i, strDate, item.Attributes["value"].Value);
                        i++;
                    }
                }
            }
            this.lvHistory.DataSource = dt;
            this.lvHistory.DataBind();
        }
        #endregion
    }
}
